<template>
  <div id="appEditPage">
    <a-page-header title="应用信息修改" @back="()=>$router.back()" />
    <a-form :model="form" :label-col="{span:4}" :wrapper-col="{span:12}" @finish="handleSubmit">
      <a-form-item label="应用名称" :rules="[{ required: true, message: '请输入名称' }]">
        <a-input v-model:value="form.appName" placeholder="请输入应用名称" />
      </a-form-item>
      <a-form-item v-if="isAdmin" label="封面">
        <a-input v-model:value="form.cover" placeholder="图片 URL" />
      </a-form-item>
      <a-form-item v-if="isAdmin" label="优先级">
        <a-input-number v-model:value="form.priority" :min="0" :max="999" />
      </a-form-item>
      <a-form-item :wrapper-col="{span:12, offset:4}">
        <a-space>
          <a-button type="primary" html-type="submit" :loading="saving">保存</a-button>
          <a-button @click="()=>$router.back()">返回</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { getMyAppById, getAppById, updateMyApp, updateApp } from '@/api/appController.ts'
import { useLoginUserStore } from '@/stores/loginUser.ts'

const route = useRoute()
const id = String(route.params.id || '')
const saving = ref(false)
const loginStore = useLoginUserStore()
const isAdmin = computed(() => loginStore.loginUser?.userRole === 'admin')

const form = reactive<Partial<API.AppVO>>({ appName: '', cover: '', priority: 0 })

const fetchDetail = async () => {
  const api = isAdmin.value ? getAppById : getMyAppById
  const res = await api({ id: id as any })
  if (res.data.code === 0 && res.data.data) {
    Object.assign(form, res.data.data)
  }
}

const handleSubmit = async () => {
  saving.value = true
  try {
    if (isAdmin.value) {
      const res = await updateApp({ id: id as any, appName: form.appName, cover: form.cover, priority: form.priority })
      if (res.data.code === 0) message.success('保存成功')
      else message.error(res.data.message)
    } else {
      const res = await updateMyApp({ id: id as any, appName: form.appName as string })
      if (res.data.code === 0) message.success('保存成功')
      else message.error(res.data.message)
    }
  } finally {
    saving.value = false
  }
}

onMounted(fetchDetail)
</script>

<style scoped></style>


